package com.lambkit.module.cms.web.directive;

import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.common.util.StringUtils;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;


/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("article")
public class ArticleDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {
        String idOrSlug = getPara(0, scope);
        CmsArticle article = getArticle(idOrSlug);

        if (article == null) {
            return;
        }

        scope.setLocal("article", article);
        renderBody(env, scope, writer);
    }

    private CmsArticle getArticle(String idOrAlias) {
        return StringUtils.isNumeric(idOrAlias)
                ? CmsArticle.service().findById(idOrAlias)
                : CmsArticle.service().findFirstByAlias(idOrAlias);
    }


    @Override
    public boolean hasEnd() {
        return true;
    }
}
